package com.mfoyou.agent.web.controller.order;

import java.text.DecimalFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.mfoyou.agent.common.dao.domain.HuawuAgentStoreSetting;
import org.mfoyou.agent.common.dao.domain.HuawuAgentWxInfo;
import org.mfoyou.agent.common.dao.domain.HuawuAlipay;
import org.mfoyou.agent.common.dao.domain.HuawuExtract;
import org.mfoyou.agent.common.dao.domain.HuawuThirdUser;
import org.mfoyou.agent.common.dao.domain.HuawuUser;
import org.mfoyou.agent.common.dao.domain.HuawuWallet;
import org.mfoyou.agent.common.entity.enums.MfoyouUserType;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.common.inf.IThirdPartInfo;
import org.mfoyou.agent.utils.common.DateUtils;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.ListObject;
import org.mfoyou.agent.utils.common.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.order.PaymentService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.service.thirdPart.AliPayService;
import com.mfoyou.agent.web.service.thirdPart.XGPushSerivce;
import com.mfoyou.agent.web.service.wx.WXBaseService;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;
import com.mfoyou.agent.web.utils.withdraw.AbstractWithDraw;
import com.mfoyou.agent.web.utils.withdraw.AliPayWithDraw;
import com.mfoyou.agent.web.utils.withdraw.DrawBackPayType;
import com.mfoyou.agent.web.utils.withdraw.PushListner;
import com.mfoyou.agent.web.utils.withdraw.UnderLineWithDraw;
import com.mfoyou.agent.web.utils.withdraw.WechatWithDraw;
import com.mfoyou.agent.web.utils.withdraw.WithDrawListener;

@Path("/extract")
@Service
public class ExtractController {

    private static final String EXTRACT_STATE = "wx:extract:push";

    @Autowired
    SessionService sessionService;
    @Autowired
    IAccount iAccount;
    @Autowired
    PaymentService paymentService;
    @Autowired
    AliPayService aliPayService;
    @Autowired
    XGPushSerivce xgPushSerivce;
    @Autowired
    RedisCacheManger redisCacheManger;
    @Autowired
    IIdentity iIdentity;
    @Autowired
    WXBaseService wxBaseService;
    @Autowired
    IThirdPartInfo iThirdPartInfo;

    /**
     * 提现申请列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @return
     */
    @GET
    @Path("extract/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> auditExtractList(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                       @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize) {
        Date startDate = DateUtils.parse(request.getParameter("startDate"));
        Date endDate = DateUtils.parse(request.getParameter("endDate"));
        Integer agentId = sessionService.currentUserId(request);
        String typeS = request.getParameter("type");
        Integer type = typeS == null ? null : Integer.valueOf(typeS);
        HuawuExtract mfoyouExtract = new HuawuExtract();
        mfoyouExtract.setExtractState(StrUtil.parseInteger(request.getParameter("extractState")));
        mfoyouExtract.setExtractAccount(request.getParameter("extractAccount"));
        String phone = request.getParameter("phoneNumber");
        if (phone != null) {
            HuawuUser userInfo = iAccount.getUserInfoByPhone(phone, agentId);
            Integer userId = userInfo.getUserId();
            mfoyouExtract.setUserId(userId);
        }
        mfoyouExtract.setAgentId(agentId);
        mfoyouExtract.setExtractAuditResult(StrUtil.parseInteger(request.getParameter("extractAuditResult")));
        mfoyouExtract.setExtractType(StrUtil.parseInteger(request.getParameter("extractType")));
        mfoyouExtract.setExtractUserType(StrUtil.parseInteger(request.getParameter("userType")));
        ListObject bulidListObject = ListObject.BulidListObject(
                paymentService.getExtractList(type, mfoyouExtract, pageId, pageSize, startDate, endDate));
        HuawuAgentStoreSetting specialSettingV1 = iIdentity.getSpecialSettingV1(agentId);
        if (specialSettingV1 != null && specialSettingV1.getRechageType() != null) {
            bulidListObject.setRechageType(specialSettingV1.getRechageType());
        }
        return JsonRet.buildRet(0, bulidListObject);
    }

    /**
     * 提现审核
     *
     * @param request
     * @param response
     * @param auditId
     * @param state
     * @param type
     * @return
     */
    @POST
    @Path("audit/extract/{auditId}/{state}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> auditExtract(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                   @PathParam("auditId") Integer auditId, @PathParam("state") Integer state,
                                   @QueryParam("type") Integer type) {
        Integer agentId = sessionService.currentUserId(request);
        if ((state != -1 && state != 1) || auditId == null) {
            return JsonRet.buildRet(-11);// 参数不对直接返回
        }
        HuawuAgentStoreSetting specialSettingV1 = iIdentity.getSpecialSettingV1(agentId);
        if (specialSettingV1.getRechageType() == null) {
            return JsonRet.buildRet(-56); // 支付方式未配置 ，存在异常
        }
        String openId = null;
        HuawuExtract mfoyouExtract = paymentService.getMfoyouExtract(auditId); // 前置优化
        if (mfoyouExtract.getExtractAuditResult() != 0) {
            return JsonRet.buildRet(-95); // 先判断，
        }
        if (specialSettingV1.getRechageType() == 1 && state == 1) {
            Integer userId = mfoyouExtract.getUserId();
            HuawuThirdUser thirdByUserId = iAccount.getThirdByUserId(userId, 200);
            if (thirdByUserId == null || thirdByUserId.getOpenId() == null) {
                return JsonRet.buildRet(-57); // 如果是微信支付先判断是否授权 悲观锁的提现
            }
            openId = thirdByUserId.getOpenId();
        }
        HuawuExtract checkExtract = new HuawuExtract();
        checkExtract.setExtractId(auditId);
        checkExtract.setExtractAuditResult(0);
        checkExtract.setAgentId(agentId);
        HuawuExtract updateExtract = new HuawuExtract();
        updateExtract.setAdminId(sessionService.currentUserId(request));
        updateExtract.setExtractAuditTime(new Date());
        updateExtract.setExtractAuditResult(state);
        updateExtract.setExtractState(state == -1 ? 3 : null);
        updateExtract.setExtractType(specialSettingV1.getRechageType() == 1 ? 2 : null);
        boolean modifyExtract = paymentService.modifyExtract(checkExtract, updateExtract);
        if (!modifyExtract) {
            return JsonRet.buildRet(-95);
        }
        // 修改成功
        if (state == 1) {
            AbstractWithDraw withDraw = null;
            Integer amount = mfoyouExtract.getExtractAmount();
            String name = mfoyouExtract.getExtractAccountName();
            String payNumber = mfoyouExtract.getExtractId() + "" + System.currentTimeMillis();
            if (type != null) {
                withDraw = new UnderLineWithDraw();
            } else if (specialSettingV1.getRechageType() == 1) {
                HuawuAgentWxInfo huawuAgentWxInfo = wxBaseService.getWxInfo(agentId, 200);
                withDraw = new WechatWithDraw(openId, name, huawuAgentWxInfo, amount, "微信提现->" + name, payNumber);
            } else if (specialSettingV1.getRechageType() == 2) {
                String extractAccount = mfoyouExtract.getExtractAccount();
                HuawuAlipay huawuAlipay = iThirdPartInfo.getAliPayByAgentId(agentId);
                withDraw = new AliPayWithDraw(mfoyouExtract.getExtractId(), amount, name, extractAccount, huawuAlipay);
            }
            int Extype = type != null ? DrawBackPayType.wallet.getValue()
                    : specialSettingV1.getRechageType() == 2 ? DrawBackPayType.alipay.getValue()
                    : DrawBackPayType.WeChat.getValue();
            withDraw.addListener(new PushListner(new HuawuExtract(auditId, Extype, payNumber), paymentService));
            // 推送系统通知
            withDraw.addListener(new WithDrawListener() {
                @Override
                public void success(String message) {
                    String title = "mfoyou提现成功通知。";
                    String content = "mfoyou提现" + formatPrice(amount) + "元成功！";
                    xgPushSerivce.pushExtractNotify(mfoyouExtract.getUserId(), auditId,
                            mfoyouExtract.getExtractUserType(), title, content);
                }

                @Override
                public void fail(String message) {
                }
            });
            return withDraw.done();
        } else if (state == -1) {
            Integer userId = mfoyouExtract.getUserId();
            Integer userType = mfoyouExtract.getExtractUserType();
            HuawuWallet mfoyouWallet = paymentService.getUserWallet(userId);
            Integer oldValue = getUserextractAmount(mfoyouWallet, userType);
            Integer amount = mfoyouExtract.getExtractAmount();
            boolean result = paymentService.returnExtractFailMoney(6, userId, oldValue, amount, auditId, userType);
            if (!result) {
                JsonRet.buildRet(-17);
            }
            if (mfoyouExtract.getExtractUserType().intValue() == MfoyouUserType.runer.getValue()) {
                String title = "提现被驳回通知";
                String content = "你的提现金额为" + formatPrice(amount) + "元的请求已被驳回，请与管理员联系";
                xgPushSerivce.pushExtractNotify(mfoyouExtract.getUserId(), auditId, mfoyouExtract.getExtractUserType(),
                        title, content);
            } else if (mfoyouExtract.getExtractUserType().intValue() == MfoyouUserType.store.getValue()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userid", mfoyouExtract.getUserId());
                jsonObject.put("result", 3);
                jsonObject.put("amount", amount);
                jsonObject.put("date", new Date().getTime());
                redisCacheManger.pushRList(EXTRACT_STATE, jsonObject.toJSONString());
            }
        }
        return JsonRet.buildRet(0);
    }

    public static int getUserextractAmount(HuawuWallet mfoyouWallet, int userType) {

        if (MfoyouUserType.agent.getValue() == userType) {
            return mfoyouWallet.getWalletAgentAmount();
        }
        if (MfoyouUserType.runer.getValue() == userType) {
            return mfoyouWallet.getWalletRunerAmount();
        }
        if (MfoyouUserType.store.getValue() == userType) {
            return mfoyouWallet.getWalletStoreAmount();
        }
        if (16 == userType) {
            return mfoyouWallet.getWalletStoreAgentAmount();
        }
        return mfoyouWallet.getWalletExtractAmount();
    }

    private static String formatPrice(Integer acount) {
        DecimalFormat df = new DecimalFormat("#0.00");
        Double intValue = (double) acount.intValue();
        return df.format(intValue / 100);
    }
}
